﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EFMysqlConsoleApplication1
{
    [Table("TOrder")]
    public class Order
    {
        public int Id { get; set; }

        public string OrderCode { get; set; }

        public int Quantity { get; set; }

        public decimal Amount { get; set; }

        public int UserId { get; set; }

        [ForeignKey("UserId")]
        public virtual User User { get; set; }

        public virtual List<OrderItem> OrderItems { get; set; }

        public void AddItem(OrderItem item)
        {
            if (OrderItems == null)
            {
                this.OrderItems = new List<OrderItem>();
            }

            this.OrderItems.Add(item);

            this.UpdateOrderByItem();
        }

        public void RemoveItem(int itemId)
        {
            if (this.OrderItems != null && this.OrderItems.Any())
            {
                var itemEntity = this.OrderItems.SingleOrDefault(item => item.Id == itemId);
                this.OrderItems.Remove(itemEntity);
                this.UpdateOrderByItem();
            }
        }

        private void UpdateOrderByItem()
        {
            this.Quantity = this.OrderItems.Sum(item => item.Quantity);
            this.Amount = this.OrderItems.Sum(item => item.Amount);
        }
    }
}
